<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="90px">
      <el-form-item label="类型编号" prop="businessCode">
        <el-input v-model="queryParams.businessCode" placeholder="请输入" clearable disabled
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="文件名字" prop="fileName">
        <el-input v-model="queryParams.fileName" placeholder="请输入" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="业务id" prop="businessId">
        <el-input v-model="queryParams.businessId" placeholder="请输入" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
        >新增</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="fileList" @selection-change="handleSelectionChange"
      :row-style="{ height: '35px' }" border :cell-style="{ padding: '0px' }">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="旧附件名字" align="center" prop="fileName" show-overflow-tooltip="true" />
      <el-table-column label="新附件名字" align="center" prop="newFileName" show-overflow-tooltip="true" />
      <el-table-column label="业务id" align="center" prop="businessId" show-overflow-tooltip="true" />
      <el-table-column label="附件类型" align="center" prop="fileType" />
      <el-table-column label="附件大小" align="center" prop="fileSize" width="90" :formatter="showFileSize" />
      <el-table-column label="访问路径" align="center" prop="url" show-overflow-tooltip="true" />
      <el-table-column label="保存路径" align="center" prop="phyPath" show-overflow-tooltip="true" />
      <el-table-column label="是否删除" align="center" prop="delFlag">
        <template slot-scope="scope">
          <span>{{ scope.row.delFlag == 0 ? '否' : '是' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="上传时间" align="center" prop="uploadTime" width="150">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.uploadTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="150">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-upload2" @click="handleUpload(scope.row)" title="上传到服务器"
           ></el-button>
          <el-button size="mini" type="text" icon="el-icon-download" @click="handleDownload(scope.row)" title="下载"
          ></el-button>
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)" title="修改"
           ></el-button>
          <el-button size="mini" type="text" icon="el-icon-view" @click="handleView(scope.row)" title="查看"
          ></el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)" title="删除"
          ></el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改附件对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-alert title="提示" type="success"
        :description="`文件上传大小不能超过${sysUpload.fileMaxSize}MB,文件上传个数不能超过${sysUpload.fileLimit}个`">
      </el-alert>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <!-- <el-form-item label="旧文件名" prop="fileName" v-if="update==1">
            <el-input v-model="form.fileName" placeholder="请输入" />
          </el-form-item> -->
        <!-- <el-form-item label="新文件名" prop="newFileName" v-if="update==1">
            <el-input v-model="form.newFileName" placeholder="请输入新文件名" />
          </el-form-item>
          <el-form-item label="文件大小" prop="fileSize" v-if="update==1">
            <el-input v-model="form.fileSize" placeholder="请输入" />
          </el-form-item>
          <el-form-item label="访问路径" prop="url" v-if="update==1">
            <el-input v-model="form.url" placeholder="请输入" />
          </el-form-item>
          <el-form-item label="保存路径" prop="PhyPath" v-if="update==1">
            <el-input v-model="form.PhyPath" placeholder="请输入" />
          </el-form-item> -->
        <el-form-item label="业务id" prop="businessId">
          <el-input v-model="form.businessId" placeholder="请输入" :disabled="update == 1" />
        </el-form-item>
        <el-upload ref="upload" :limit="sysUpload.fileLimit" :accept="fileType" :action="upload.url"
          :headers="upload.headers" :file-list="upload.fileList" :on-progress="handleFileUploadProgress"
          :on-success="handleFileSuccess" :before-upload="handleBeforeUpload" :on-change="handelChange"
          :data="upload.data" :on-error="handleUploadError" :auto-upload="false">
          <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
          <el-button style="margin-left: 10px;" size="small" type="success" :loading="upload.isUploading"
            @click="submitUpload">上传到服务器</el-button>
          <div slot="tip" class="el-upload__tip">只能上传{{ fileType }}文件，且不超过{{ sysUpload.fileMaxSize }}MB</div>
        </el-upload>
        <el-form-item label="备注">
          <el-input type="textarea" v-model="form.content" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm" v-if="update == 1">确 定</el-button>
        <el-button @click="cancel">关 闭</el-button>
      </div>
    </el-dialog>
    <el-dialog :title="uploadTitle" :visible.sync="uploadOpen" width="700px" append-to-body>
      <upload-file :value="1" :limit="2" :fileSize="5" v-if="uploadOpen" :type="0" :businessId="businessId"
        :businessCode="businessCode"></upload-file>
    </el-dialog>
    <el-dialog :title="viewTitle" :visible.sync="viewOpen" width="700px" append-to-body>
      <el-descriptions title="附件信息" column="2">
        <el-descriptions-item label="旧附件名：">{{ viewFile.fileName }}</el-descriptions-item>
        <el-descriptions-item label="新附件名">{{ viewFile.newFileName }}</el-descriptions-item>
        <el-descriptions-item label="业务id">{{ viewFile.businessId }}</el-descriptions-item>
        <el-descriptions-item label="附件大小">{{ showFileSize(viewFile) }} </el-descriptions-item>
        <el-descriptions-item label="附件类型">
          <el-tag size="small"> {{ viewFile.fileType }}</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="访问路径">{{ viewFile.url }} </el-descriptions-item>
        <el-descriptions-item label="保存路径">{{ viewFile.phyPath }}</el-descriptions-item>
        <el-descriptions-item label="上传时间">{{ viewFile.uploadTime }}</el-descriptions-item>
      </el-descriptions>
      <div slot="footer" class="dialog-footer">
        <el-button @click="uploadCancel">关 闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listFile, getFile, delFile, addFile, updateFile } from "@/api/system/file";
import { selectUploadByCode } from "@/api/system/upload";
import { getToken } from "@/utils/auth";
import { download } from "@/utils/request";
import UploadFile from "@/components/FileUpload/index"
export default {
  name: "File",
  components: { UploadFile },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 附件表格数据
      fileList: [],
      // 弹出层标题
      title: "",
      uploadTitle: "",
      // 是否显示弹出层
      open: false,
      uploadOpen: false,
      viewOpen: false,
      //上传文件后缀名
      fileType: '',
      // 上传参数
      upload: {
        data: {},
        // 是否禁用上传
        isUploading: false,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/common/upload",
        // 上传的文件列表
        fileList: []
      },
      //类型编号
      businessCode: 'test',
      //业务id
      businessId: 121,
      data: [],
      fileData: [],
      //文件详情
      viewFile: {},
      sysUpload: { fileLimit: 1 },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 15,
        businessCode: null,
        fileName: null,
        fileType: null,
        fileSize: null,
        url: null,
        PhyPath: null,
        content: null,
        operateTime: null,
        operateId: null,
        departmentId: null,
        departmentName: null,
        organizationId: null,
        organizationName: null,
        creationTime: null,
        creationBy: null,
        newFileName: null,
        businessId: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        businessId: [
          { required: true, message: "业务id不能为空", trigger: "blur" },
        ],
      },
      update: 0,
    };
  },
  created() {
    const businessCode = this.$route.params && this.$route.params.businessCode;
    if (businessCode) {
      this.upload.data["businessCode"] = businessCode
      this.queryParams.businessCode = businessCode
      this.files(businessCode);
    }

    this.getList();
  },
  methods: {
    /** 查询附件列表 */
    getList() {
      this.loading = true;
      listFile(this.queryParams).then(response => {
        this.fileList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 文件上传
    submitUpload() {
      this.upload.data["businessId"] = this.form.businessId
      this.upload.data["content"] = this.form.content
      //修改
      if (this.update == 1) {
        this.upload.data["id"] = this.form.id
      }
      else {

        delete this.upload.data.id
      }
      if (this.$refs["form"].validate()) {
        this.$refs.upload.submit();
      }

    },
    handelChange(file, fileList) {
      this.upload.fileList = fileList
    },
    uploadFile(file) {
      console.log("自定义上传文件", file);
    },
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    handleFileSuccess(response, file, fileList) {
      this.upload.isUploading = false;
      this.$modal.closeLoading()
      this.open = false;
      this.getList()
    },
    handleBeforeUpload(file) {
      if (file.size / 1024 / 1024 > Number(this.sysUpload.fileMaxSize)) {
        this.$modal.msgError(`上传文件大小不能超过 ${this.sysUpload.fileMaxSize} MB!`);
        return false
      }
      this.$modal.loading("正在上传文件，请稍候...");
      return true;
    },
    handleUpload() {
      this.uploadOpen = true
      this.uploadTitle = "上传"
    },
    //文件下载
    handleDownload(row) {
      let params = {
        resource: row.url
      }
      download("/common/download/resource", params, row.newFileName);
    },
    files(code) {
      selectUploadByCode(code).then(response => {
        this.fileType = response.data.type
        this.sysUpload = response.data
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    uploadCancel() {
      console.log()
      this.viewOpen = false
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        businessCode: null,
        fileName: null,
        fileType: null,
        fileSize: null,
        url: null,
        PhyPath: null,
        content: null,
        operateTime: null,
        operateId: null,
        departmentId: null,
        departmentName: null,
        organizationId: null,
        organizationName: null,
        creationTime: null,
        creationBy: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.upload.fileList = [];
      this.reset();
      this.open = true;
      this.update = 0
      this.title = "新增";
    },
    handleView(row) {
      this.reset();
      const id = row.id || this.ids
      getFile(id).then(response => {
        this.viewTitle = "";
        this.viewOpen = true;
        this.viewFile = response.data
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getFile(id).then(response => {
        this.upload.fileList = []
        this.form = response.data;
        this.open = true;
        this.update = 1
        this.sysUpload.fileLimit = 1
        let file = { url: response.data.url, name: response.data.fileName }
        this.upload.fileList.push(file)
        this.title = "修改附件";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            let data = { id: this.form.id, content: this.form.content }
            updateFile(data).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addFile(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    showFileSize(row, column, cellValue, index) {
      let value = (row.fileSize / 1024).toFixed(1)
      return value + "KB"
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除附件？').then(function () {
        return delFile(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/file/export', {
        ...this.queryParams
      }, `file_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
